package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.entity.Account;
import com.example.entity.User;
import com.example.exception.CustomerException;
import com.example.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserService {


    @Autowired
    UserMapper userMapper;


    public String user(String name) {
        if ("user".equals(name)) {
            return "请求成功";
        } else {
            throw new CustomerException("账号错误");
        }
    }


    public void add(User user) {
// 根据新的账号查询数据库 是否存在同样的账号的数据
      User dbUser  =  userMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            throw new CustomerException("账号重复");
        }
        //默认密码
      if(StrUtil.isBlank(user.getPassword())){
            user.setPassword("123");
        }
        if(StrUtil.isBlank(user.getPassword())){
            user.setName(user.getName());
        }
      user.setRole("USER");
        userMapper.insert(user);
    }
    //修改
    public void update(User user) {
            userMapper.updateById(user);
    }
    //删除
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
        System.out.println("执行删除操作，ID：" + id); // 添加日志
        userMapper.deleteById(id);
    }
    //JWT
    public Account selectById(String id) {
        return userMapper.selectById(id);
    }
    //查询
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }
    //批量删除

    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize, User user) {
   //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }


    public User login(Account account) {
        // 验证账号是否存在
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (dbUser == null) {
            throw new CustomerException("账号不存在");
        }
        // 验证密码是否正确
        if (!dbUser.getPassword().equals(account.getPassword())) {
            throw new CustomerException("账号或密码错误");
        }
        return dbUser;
    }

    public void register(User user) {
        this.add(user);
    }


    public void deleteBatch(List<User> list) {
        // 提取用户 ID 列表
        List<Integer> idList = list.stream()
                .map(User::getId)
                .filter(Objects::nonNull) // 替换为方法引用，消除 IDE 提示
                .collect(Collectors.toList()); // 确保拼写正确

        // 调用批量删除
        if (!idList.isEmpty()) {
            userMapper.deleteBatch(idList);
        }
    }



}
